<?php
/**
 * Created by PhpStorm.
 * User: xuzhong
 * Date: 2025/4/2
 * Time: 13:49
 */
namespace app\admin\service;

use app\admin\common\ServiceResponse;
use app\admin\model\Images;
use app\admin\model\ManualBook as ManualBookModel;
use think\facade\Db;

class ManualBook extends BaseService
{
    use ServiceResponse;

    protected $model;

    public function __construct()
    {
        $this->model = new ManualBookModel();
        parent::__construct();
    }

    /**
     * @describe 获取销售人员列表
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function getList($where, $page, $limit, $type): array
    {
        if (0 >= $page || 100 < $limit) {
            return $this->error(100002);
        }

        $total = $this->model->where($where)->count();
        if (!$total) {
            return $this->success(['list' => [], 'total' => 0]);
        }
        $list = $this->model->where($where)
            ->page($page, $limit)
            ->order('create_time desc')
            ->select()->toArray();

        // 获取所有pids字段
        $pidsArray = array_column($list, 'pids');

        // 处理逗号分隔的字符串，合并为一维数组
        $allPids = [];
        foreach ($pidsArray as $pidsString) {
            if (!empty($pidsString)) {
                // 将逗号分隔的字符串拆分为数组
                $splitPids = explode(',', $pidsString);
                // 合并到总数组中
                $allPids = array_merge($allPids, $splitPids);
            }
        }

        // 去重、过滤空值、转换为整数
        $pids = array_unique(array_filter(array_map('intval', $allPids)));
        // 重新索引数组
        $pids = array_values($pids);

        // 根据type获取不同表的产品名称
        $product = [];
        foreach ($list as $item) {
            if (!empty($item['pids'])) {
                $currentPids = explode(',', $item['pids']);
                if ($type == 1) {
                    // 从 product 表获取名称
                    $productNames = Db::name('product')
                        ->where('id', 'in', $currentPids)
                        ->field('id,cname')
                        ->select()
                        ->toArray();
                    foreach ($productNames as $p) {
                        $product[$p['id']] = $p['cname'];
                    }
                } elseif ($type == 2) {
                    // 从 product_merge 表获取名称
                    $productNames = Db::name('product_merge')
                        ->where('id', 'in', $currentPids)
                        ->field('id,productname')
                        ->select()
                        ->toArray();
                    foreach ($productNames as $p) {
                        $product[$p['id']] = $p['productname'];
                    }
                }
            }
        }

        $avatorId = array_unique(array_column($list,'file_id'));
        $avatorId = implode(',',$avatorId);
        #获取图片url
        $oImages = new Images();
        $avatorUrls = $oImages->getImagesByIds($avatorId);
        $avatorUrls = array_column($avatorUrls, null, 'id');

        foreach ($list as $k=>$v) {
            $list[$k]['product_list'] = '';
            // 处理文件列表
            $list[$k]['file_list'] = [];
            if ($v['file_id']) {
                $fileIds = explode(',', $v['file_id']);
                foreach ($fileIds as $fileId) {
                    if (isset($avatorUrls[$fileId])) {
                        $list[$k]['file_list'][] = [
                            'file_id' => $fileId,
                            'file_url' => $avatorUrls[$fileId]['url'] ?? '',
                            'file_name' => $avatorUrls[$fileId]['name'] ?? ''
                        ];
                    }
                }
            }
            // 保持原有的单文件字段，使用第一个文件的信息（向后兼容）
            if (!empty($list[$k]['file_list'])) {
                $firstFile = $list[$k]['file_list'][0];
                $list[$k]['file_url'] = $firstFile['file_url'];
                $list[$k]['file_name'] = $firstFile['file_name'];
                $list[$k]['file_id'] = $firstFile['file_id'];
            } else {
                $list[$k]['file_url'] = '';
                $list[$k]['file_name'] = '';
                $list[$k]['file_id'] = '';
            }

            if($v['pids']){
                $pids = explode(',',$v['pids']);
                $pids_name = [];
                foreach($pids as $pid){
                    if(!empty($product[$pid])){
                        $pids_name[] = $product[$pid];
                    }
                }
                $list[$k]['product_list'] = implode(',',$pids_name);
            }
        }

        return $this->success(['list' => $list, 'total' => $total]);
    }
    /**
     * 创建销售人员
     * @param array $data 创建物流公司的数据
     */
    public function create($data)
    {
        if(!empty($data)){
            try {

                $res = $this->model->create($data);
                if ($res) {

                    $this->logger->logOperation($res->id,'ManualBook','创建','创建手册');
                    return $this->success();
                } else {
                    return $this->error(500001);
                }
            } catch (\Throwable $th) {
                return $this->error(500001, '服务器内部错误：' . $th->getMessage());
            }
        }else{
            return $this->error(500001, '服务器内部错误' );
        }

    }
    /**
     * 获取销售人员详情
     * @param int $id 物流公司ID
     */
    public function getOneById($id)
    {
        $customerContact = $this->model->find($id);
        if ($customerContact) {
            $data = $customerContact->append(['creator_value']);
        }
        $data = $data->toArray();
        return $this->success($data);
    }
    /**
     * 更新销售人员
     * @param int $id 物流公司ID
     * @param array $data 更新物流公司的数据
     */
    public function update($data)
    {
        $res = $this->model->where('id', $data['id'])->find();
        if (!$res) {
            return false;
        }
        foreach ($data as $key => $value) {
            if ($res->$key != $value) {
                $res->$key = $value;
            }
        }

        $result = $res->save();
        if ($result) {
            $this->logger->logOperation($res->id,'ManualBook','更新','更新手册');
            return $this->success();
        } else {
            return $this->error(500001);
        }
    }

    /**
     * @describe 删除销售人员
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function delete($param): array
    {
        #校验参数
        if (!isset($param['ids']) || empty($param['ids'])) {
            return $this->error(100001, '操作失败');
        }
        #查询数据是否存在
        $result =$this->model->where('id', 'in', $param['ids'])->where('is_del', '=', 0)->select()->toArray();

        if (!empty($result)) {
            #更新记录
            $update = $this->model->where('id', 'in', $param['ids'])->where('is_del', '=', 0)->update([
                'is_del' => time()
            ]);
            if ($update) {
                #同事删除支持货币
                Db::name('miner_pool_support_currency')->whereIn('miner_pool_id',$param['ids'])->update([
                    'is_del' => time()
                ]);
                #尝试记录操作日志 不影响主流程
                try {
                    $this->logger->logOperation($param['ids'], 'Minerpool', '删除', '删除矿池');
                } catch (\Exception $e) {
                    #记录日志或其他操作
                }
                return $this->success();
            } else {
                return $this->error(500001, '操作失败');
            }

        } else {
            #未找到记录返回失败
            return $this->error(400000, '未找到相关数据');
        }
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-02-13 11:03:36
     * @param [type] @required
     * @return Renderable
     */
    public function getFieldEnum($field = 'all')
    {
        $res = $this->model->getFieldEnum($field);
        return [
            'code' => 0,
            'data' => $res
        ];
    }
}
